package org.example;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPubSub;

/**
 * @Auther: wangbw
 * @Date:2020/10/3
 * @Description: org.example
 * @version: 1.0
 */
public class PubSubDemo {
    public static void main(String[] args) throws InterruptedException {
        final String key = "abc";
        final Jedis jedis = new Jedis();
        final MessagePubSub sub = new MessagePubSub();

        Thread task1 = new Thread(
                new Runnable() {
                    @Override
                    public void run() {
                        try {
                            jedis.subscribe(sub,key);
                            System.out.println("ending listen");
                            jedis.close();
                        } catch (Exception e) {
                            System.out.println(e);
                        } finally {
                            if (jedis != null)
                                jedis.close();
                        }
                    }
                }
        );
        task1.start();
        Thread.sleep(500);
        Jedis jedis2 = new Jedis();
        jedis2.publish(key, "I love You");
        jedis2.close();
        Thread.sleep(1000*90L);
    }

    static class MessagePubSub extends JedisPubSub {
        @Override
        public void onMessage(String channel, String message) {
            System.out.printf("onMessage-- channel：%smessage：%s\r\n", channel, message);
        }

        @Override
        public void onSubscribe(String channel, int subscribedChannels) {
            super.onSubscribe(channel, subscribedChannels);
            System.out.printf("onSubscribe-- channel：%smessage：%s\r\n", channel, subscribedChannels);
        }

        @Override
        public void onUnsubscribe(String channel, int subscribedChannels) {
            super.onUnsubscribe(channel, subscribedChannels);
            System.out.printf("onUnsubscribe-- channel：%smessage：%s\r\n", channel, subscribedChannels);
        }
    }
}
